package com.gict.antifraudback.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gict.antifraudback.utils.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.concurrent.TimeUnit;


/**
 * 响应处理拦截器
 *
 * @author
 */
public class MyResponseBodyAdvice implements ResponseBodyAdvice {

    @Value("${cache.enable}")
    private boolean enable;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 判断是否支持
     *
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return enable && methodParameter.hasMethodAnnotation(GetMapping.class) &&
                methodParameter.hasMethodAnnotation(Cache.class);
    }

    /**
     * @param o
     * @param methodParameter
     * @param mediaType
     * @param aClass
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //无数据直接返回null
        if (null == o) {
            return null;
        }
        try {
            //判断是否是string,不是转成json
            String redisValue = null;
            if (o instanceof String) {
                redisValue = (String) o;
            } else {
                redisValue = OBJECT_MAPPER.writeValueAsString(o);
            }

            String redisKey = RedisCacheInterceptor.createRedisKey(((ServletServerHttpRequest) serverHttpRequest).getServletRequest());

            Cache methodAnnotation = methodParameter.getMethodAnnotation(Cache.class);

            //获取cache注解中的时间进行缓存，缓存的时间单位是秒
            assert methodAnnotation != null;
            this.redisTemplate.opsForValue().set(redisKey, redisValue, Long.parseLong(methodAnnotation.time()), TimeUnit.SECONDS);

            return o;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
